<template>
  <div class="login">
    <div class="login-box">
      <div class="login-main">
        <!-- <div class="login-left">
          <img :src="loginXuanImg" alt="" />
        </div> -->
        <div class="login-right">
          <div class="login-form-box">
            <div class="login-form-top">
              <!-- <img :src="logoImg" alt="" /> -->
            </div>
            <div class="login-form-title">BLOG控制台</div>
            <VTab class="login-tab" v-model="tabIndex" :tabsData="tabList"></VTab>
            <div v-if="tabIndex == 0">
              <el-form ref="formPasswordRef" :model="formData" :rules="passwordRules" class="login-form"
                label-position="top" size="large" @keyup.enter="handlelogin">

                <el-form-item prop="userName" label="用户名">
                  <el-input ref="userName" v-model="formData.userName" placeholder="请输入用户名" type="text" maxlength="11"
                    clearable />
                </el-form-item>

                <el-form-item prop="password" label="密码">
                  <el-input ref="passwordRef" v-model="formData.password" :key="passwordType" :type="passwordType"
                    placeholder="请输入密码" />
                  <span class="show-pwd" @click="showPwd">
                    <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'
                      " />
                  </span>
                </el-form-item>
              </el-form>
            </div>
            <div v-else>
              <el-form ref="formCodeRef" :model="formData" :rules="codeRules" class="login-form" label-position="top"
                size="large" @keyup.enter="handlelogin">
                <el-form-item prop="phone" label="手机号">
                  <el-input ref="phone" v-model="formData.phone" placeholder="请输入手机号" type="text" maxlength="11"
                    clearable />
                </el-form-item>
                <el-form-item prop="code" label="验证码">
                  <el-input v-model.trim="formData.code" placeholder="请输入验证码" type="text" maxlength="6"
                    style="width: 256px" clearable />
                  <el-button class="veri-btn" type="primary" size="large" @click="loginCodeFun"
                    :loading="timeNum !== tolNum">
                    {{ timeNum === tolNum ? '点击验证' : timeNum }}
                  </el-button>
                  <div class="code-tip" v-if="showCodeTip">验证码已发送,10分钟内有效</div>
                </el-form-item>
              </el-form>

            </div>
            <div class="forget-box">
              <a @click="goEdit()">忘记密码</a>
              <div></div>
            </div>
            <div class="bottom-box">
              <el-button class="lg-btn" size="large" :loading="loading" type="primary" @click.prevent="handlelogin">
                登录
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import router from '@/router';
// 状态管理依赖
import { useUserStoreHook } from '@/store/modules/user';
// API依赖
import { useRoute } from 'vue-router';
import { valTime } from '@/utils/utils';
import { loginCode, postPhoneCode } from '@/api/user';

const route = useRoute();
const userStore = useUserStoreHook();

const formCodeRef = ref(ElForm);
const formPasswordRef = ref(ElForm);
const passwordRef = ref(ElInput);
const loginXuanImg = new URL('@/assets/index/login-xuan.png', import.meta.url).href
const logoImg = new URL('@/assets/index/logo.png', import.meta.url).href

const state = reactive({
  redirect: '',
  tabIndex: 0,
  tabList: [
    {
      label: '帐户密码登录',
    },
    {
      label: '手机号登录',
    },
  ],
  formData: {
    areaCode: '86',
    phone: '13612345611',
    userName: 'admin',
    password: '123456',
    code: '123456',
  } as any,
  passwordRules: {
    // phone: [
    //   {
    //     required: true,
    //     message: "手机号码非法",
    //     trigger: "blur",
    //     pattern: /^1\d{10}$/,
    //   },
    // ],
    userName: [
      {
        required: true,
        message: "用户名不能为空",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入6-20位数数字和字母组合的密码',
        min: 6,
        max: 20
      }
    ],
  },
  codeRules: {
    phone: [
      {
        required: true,
        message: "手机号码非法",
        trigger: "blur",
        pattern: /^1\d{10}$/,
      },
    ],
    code: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入4-6位数验证码',
        min: 4,
        max: 6
      }
    ]
  },
  loading: false,
  showCodeTip: false,
  passwordType: 'password',
  otherQuery: {},
});

const {
  formData,
  codeRules,
  passwordRules,
  loading,
  passwordType,
  showCodeTip,
  tabIndex,
  tabList
} = toRefs(state);

const { setTime, resetTime, timeNum, tolNum } = valTime();

function goEdit() {
  router.push({ path: '/editPass', query: { phone: formData.value.phone } });
}

function goRegister() {
  router.push({ path: '/register', query: {} });
}

function showPwd() {
  if (passwordType.value === 'password') {
    passwordType.value = '';
  } else {
    passwordType.value = 'password';
  }
  nextTick(() => {
    passwordRef.value.focus();
  });
}

async function loginCodeFun(params: any) {
  formCodeRef.value.validate((valid: boolean) => {
    if (valid) {
      // 发送验证码
      setTime();
      showCodeTip.value = true;
      loginCode(formData.value)
        .then((res: any) => {
          ElMessage.success('发送成功',);
          if (res.code != '000000') {
            resetTime()
          }
        })
    }
  });
}

/**
 *  登录处理
 */
function handlelogin() {
  let validateRef = tabIndex.value == 0 ? formPasswordRef : formCodeRef
  validateRef.value.validate((valid: boolean) => {
    // console.log(valid);
    if (valid) {
      state.loading = true;
      userStore
        .login({ ...state.formData, tabIndex: tabIndex.value })
        .then((res: any) => {
          console.log('登录成功', res)
          state.loading = false;
          router.push('/dashboard')
        })
        .catch(() => {
          state.loading = false;
        });
    }
  });
}

watch(
  route,
  () => {
    const query = route.query;
    if (query) {
      state.redirect = query.redirect as string;
      state.otherQuery = getOtherQuery(query);
    }
  },
  {
    immediate: true
  }
);

function getOtherQuery(query: any) {
  return Object.keys(query).reduce((acc: any, cur: any) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur];
    }
    return acc;
  }, {});
}

onMounted(() => {

});
</script>
<style lang="scss">
@import '@/styles/index';

.login-tab {
  .el-tabs__nav {
    width: 100%;

    .el-tabs__item {
      width: 50% !important;
      text-align: center !important;
    }
  }
}


.login {
  // background-image: url('@/assets/index/login-bg1.png');
  background-size: cover;
  background-repeat: no-repeat;
  height: 100vh;
  background: #ff9933;

  .login-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .login-main {
      display: flex;

      .forget-box {
        display: flex;
        justify-content: space-between;
        color: rgba(72, 128, 255, 0.6);
      }

      .login-right {
        .login-form-box {
          background: #ffffff;
          border: 0.3px solid #b9b9b9;
          border-radius: 24px;
          height: 600px;
          width: 480px;
          border-radius: 24px;
          box-sizing: border-box;
          padding: 24px 30px;
          margin-top: 30px;

          .login-form-title {
            color: #202224;
            text-align: center;
            font-weight: 600;
            font-size: 22px;
            margin-top: 20px;
            margin-bottom: 25px;
          }

          .login-form-top {
            img {
              height: 40px;
            }
          }

          .login-form {
            .bottom-box {
              .lg-btn {
                width: 100%;
              }
            }

            .el-form-item {
              .el-form-item__label {
                font-size: 18px !important;
              }
            }

            .veri-btn {
              width: 114px;
              margin-left: 16px;
            }


          }
        }
      }

      .login-left {
        img {
          width: 624px;
        }
      }
    }
  }
}
</style>
